<?php

namespace App\Kuafu\Banner\Validate;

use App\Http\Validate\AbstractBaseValidate;
use App\Kuafu\Banner\Enum\BannerEnum;
use App\Kuafu\Banner\Model\BannerCommonModel;
use App\Kuafu\Base\Model\BaseModel;
use App\Kuafu\Base\Validate\BaseValidate;
use App\Kuafu\CouponPackage\Enum\CouponPackageEnum;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;

class BannerCommonValidate extends BaseValidate
{
    /**
     * 获取规则信息
     *
     * @param array $fields
     * @return string[]
     */
    public static function getRules(array $fields = []): array
    {
        return self::getActuallyRules([
            'type'          => 'required|integer|in:' . implode(',', array_keys(BannerEnum::TYPE_MAP)),
            'shopType'      => 'required|int|in:' . implode(',', array_keys(CouponPackageEnum::SHOP_TYPES)),
            'name'          => [
                'required',
                'string',
                'max:255',
//                Rule::unique(BannerCommonModel::class)->where('isDeleted', BaseModel::DELETE_NO)
            ],
            'effectiveType' => 'required|in:' . implode(',', array_keys(BannerEnum::EFFECTIVE_TYPE)),
            'startAt'       => vsprintf(
                'exclude_unless:effectiveType,%d|required|date_format:Y-m-d',
                [BannerEnum::EFFECTIVE_TYPE_TIME_RANGE]
            ),
            'endAt'         => vsprintf(
                'exclude_unless:effectiveType,%d|required|date_format:Y-m-d|compareDateTime:startAt',
                [BannerEnum::EFFECTIVE_TYPE_TIME_RANGE]
            ),
            'img' =>
                vsprintf(
                    'exclude_unless:type,%d|required|string|max:255',
                    [
                        BannerEnum::TYPE_INDEX,
                        BannerEnum::TYPE_BANNER,
                        BannerEnum::TYPE_AUXILIARY_SCREEN,
                        BannerEnum::TYPE_POP
                    ]
                ),
            'extraImg' =>
                vsprintf(
                    'exclude_unless:type,%d|required|string|max:255',
                    [BannerEnum::TYPE_INDEX]
                ),
            'sort'          => 'required|integer',
            'bannerType'    => 'integer',
            'status'        => 'required|integer|in:' . implode(',', array_keys(BannerEnum::STATUS_MAP)),

            'id'           => [
                'required',
                Rule::exists(BannerCommonModel::class)->where('isDeleted', BaseModel::DELETE_NO)
            ],
            "resourceType" => [
                Rule::requiredIf(function () {
                    return in_array(request()->post("type"), array_keys(BannerEnum::TYPE_TV_GROUP));
                }),
                "in:" . implode(",", array_keys(BannerCommonModel::RESOURCE_TYPE_TEXT))
            ],
            'imgs'      =>
                vsprintf(
                    'exclude_unless:type,%d|required|array',
                    array_keys(BannerEnum::TYPE_TV_GROUP)
                ),
            'productId' => 'integer',
        ], $fields);
    }


    /**
     * @param array $requestParams
     * @return array
     */
    public static function bannerInsertValidate(array $requestParams): array
    {
        $errMsgAll = '';
        list($errMsg, $bannerParams) = self::insertValidate($requestParams);
        $errMsgAll .= $errMsg;
        list($errMsg, $bannerShopParams) = BannerCommonShopMappingsValidate::insertValidate($requestParams);
        $errMsgAll .= $errMsg;

        return [$errMsgAll, $bannerParams, $bannerShopParams];
    }

    /**
     * @param array $requestParams
     * @return array
     */
    public static function insertValidate(array $requestParams): array
    {
        Validator::extend('compareDateTime',
            function ($attribute, $value, $parameters, \Illuminate\Validation\Validator $validator) {
                $validator->requireParameterCount(1, $parameters, 'compareDateTime');
                $comparedToValue = $validator->getData()[$parameters[0]];
                return strtotime($value) >= strtotime($comparedToValue);
            }, '有效期配置非法');

        return self::baseValidate(
            $requestParams,
            [
                'type',
                'shopType',
                'name',
                'effectiveType',
                'startAt',
                'endAt',
                'img',
                'extraImg',
                'sort',
                'bannerType',
                'resourceType',
                'imgs',
                'productId',
            ],
            ['name.unique' => '名称重复，请重新填写！'],
            function (array $params) {
                if ($params['type'] != BannerEnum::TYPE_INDEX) {
                    $params['extraImg'] = '';
                }

                switch ($params['effectiveType']) {
                    case BannerEnum::EFFECTIVE_TYPE_TIME_RANGE:
                        $params['startAt'] = strtotime($params['startAt']);
                        $params['endAt']   = strtotime($params['endAt']) + 24 * 60 * 60 - 1;
                        break;
                    case BannerEnum::EFFECTIVE_TYPE_ALWAYS:
                        $params['startAt'] = $params['endAt'] = 0;
                        break;
                }

                if (isset($params['imgs'])) {
                    $params['imgs'] = json_encode($params['imgs']);
                } else {
                    $params['imgs'] = json_encode([]);
                }

                return $params;
            }
        );
    }


    /**
     * @param array $requestParams
     * @return array
     */
    public static function bannerEditValidate(array $requestParams): array
    {
        $errMsgAll = '';
        list($errMsg, $bannerParams) = self::editValidate($requestParams);
        $errMsgAll .= $errMsg;
        list($errMsg, $bannerShopParams) = BannerCommonShopMappingsValidate::insertValidate($requestParams);
        $errMsgAll .= $errMsg;

        return [$errMsgAll, $bannerParams, $bannerShopParams];
    }

    /**
     * @param array $requestParams
     * @return array
     */
    public static function editValidate(array $requestParams): array
    {
        Validator::extend('compareDateTime',
            function ($attribute, $value, $parameters, \Illuminate\Validation\Validator $validator) {
                $validator->requireParameterCount(1, $parameters, 'compareDateTime');
                $comparedToValue = $validator->getData()[$parameters[0]];
                return strtotime($value) >= strtotime($comparedToValue);
            }, '有效期配置非法');

        return self::baseValidate(
            $requestParams,
            [
                'id',
                'type',
                'shopType',
                'name',
                'effectiveType',
                'startAt',
                'endAt',
                'img',
                'extraImg',
                'sort',
                'imgs',
                'productId',
                'bannerType',
            ],
            ['name.unique' => '名称重复，请重新填写！'],
            function (array $params) {
                if ($params['type'] != BannerEnum::TYPE_INDEX) {
                    $params['extraImg'] = '';
                }

                switch ($params['effectiveType']) {
                    case BannerEnum::EFFECTIVE_TYPE_TIME_RANGE:
                        $params['startAt'] = strtotime($params['startAt']);
                        $params['endAt']   = strtotime($params['endAt']) + 24 * 60 * 60 - 1;
                        break;
                    case BannerEnum::EFFECTIVE_TYPE_ALWAYS:
                        $params['startAt'] = $params['endAt'] = 0;
                        break;
                }

                if (isset($params['imgs'])) {
                    $params['imgs'] = json_encode($params['imgs']);
                } else {
                    $params['imgs'] = json_encode([]);
                }

                return $params;
            }
        );
    }

    /**
     * 状态修改校验
     *
     * @param array $requestParams
     * @return array
     */
    public static function statusValidate(array $requestParams): array
    {
        return self::baseValidate($requestParams, ['status', 'id']);
    }

    /**
     * 删除校验
     *
     * @param array $requestParams
     * @return array
     */
    public static function delValidate(array $requestParams): array
    {
        return self::baseValidate($requestParams, ['id']);
    }

}
